package main;

import java.sql.*; // JDBC stuff.
import java.io.*;  // Reading user input.

public class StudentPortal
{
	/* This is the driving engine of the program. It parses the
	 * command-line arguments and calls the appropriate methods in
	 * the other classes.
	 *
	 * You should edit this file in two ways:
	 * 	1) 	Insert your database username and password (no @medic1!)
	 *		in the proper places.
	 *	2)	Implement the three functions getInformation, registerStudent
	 *		and unregisterStudent.
	 */
	public static void main(String[] args)
	{
		if (args.length == 1) {
			try {
				DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
				String url = "jdbc:oracle:thin:@http://tycho.ita.chalmers.se:1521/kingu.ita.chalmers.se";
				String userName = "vtda357_007"; // Your username goes here!
				String password = "asdasd"; // Your password goes here!
				Connection conn = DriverManager.getConnection(url,userName,password);

				String student = args[0]; // This is the identifier for the student.
				BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
				System.out.println("Welcome!");
				while(true) {
					System.out.println("Please choose a mode of operation:");
					System.out.print("? > ");
					String mode = input.readLine();
					if ((new String("information")).startsWith(mode.toLowerCase())) {
						/* Information mode */
						getInformation(conn, student);
					} else if ((new String("register")).startsWith(mode.toLowerCase())) {
						/* Register student mode */
						System.out.print("Register for what course? > ");
						String course = input.readLine();
						registerStudent(conn, student, course);
					} else if ((new String("unregister")).startsWith(mode.toLowerCase())) {
						/* Unregister student mode */
						System.out.print("Unregister from what course? > ");
						String course = input.readLine();
						unregisterStudent(conn, student, course);
					} else if ((new String("quit")).startsWith(mode.toLowerCase())) {
						System.out.println("Goodbye!");
						break;
					} else {
						System.out.println("Unknown argument, please choose either information, register, unregister or quit!");
						continue;
					}
				}
				conn.close();
			} catch (SQLException e) {
				System.err.println(e);
				System.exit(2);
			} catch (IOException e) {
				System.err.println(e);
				System.exit(2);
			}
		} else {
			System.err.println("Wrong number of arguments");
			System.exit(3);
		}
	}

	static void getInformation(Connection conn, String student)
	{
		String getStudent = ("SELECT *" +
				" FROM StudentsFollowing" +
				" WHERE studentID = " + "'"+student+"'");
		
		String getFinishedCourses = ("SELECT *" + " FROM FinishedCourses" + 
				" WHERE student = " + "'"+student+"'");
		
		String getRegistrations = ("SELECT *" + " FROM Registrations" + 
				" WHERE student = " +"'"+student+"'");
		
		
		String getPathToGrad = ("SELECT *" + " FROM PathToGraduation" + 
				" WHERE student = " +"'"+student+"'");
		
		try {
			
			Statement stmt = conn.createStatement();
			ResultSet students = stmt.executeQuery(getStudent);
			Statement pcStmt = conn.createStatement();
			ResultSet finishedCourses = pcStmt.executeQuery(getFinishedCourses);
			Statement reStmt = conn.createStatement();
			ResultSet registrations = reStmt.executeQuery(getRegistrations);
			Statement paStmt = conn.createStatement();
			ResultSet pathToGrad = paStmt.executeQuery(getPathToGrad);
			
			
			
			while(students.next()){
				String name = students.getString(2);
				String programme = students.getString(3);
				String branch = students.getString(4);
				System.out.println("Name: " + name);
				System.out.println("Line: " + programme);
				System.out.println("Branch: " + branch + "\n");
			}
			
		
			System.out.println("Read courses (name (code) credits: grade):");
			
			while(finishedCourses.next()) {
				String fCourseName = finishedCourses.getString(3);
				String fCourse = finishedCourses.getString(4);
				String fGrade = finishedCourses.getString(5);
				double fCredit = finishedCourses.getDouble(6);
				System.out.println("\t" + fCourseName + " (" + fCourse + "), " + fCredit + "p, " + fGrade);
			}
			
			System.out.println("\n" + "Registered courses (name (code), credits: status):");
			
			while(registrations.next()) {
				String rCourseName = registrations.getString(3);
				String rCourse = registrations.getString(5);
				String rCredit = registrations.getString(4);
				String rStatus = registrations.getString(6);
				System.out.println("\t" + rCourseName + " (" + rCourse + "), " + rCredit + "p, " + rStatus);
			}
			
		
			while(pathToGrad.next()) {
				int seminarCourse = pathToGrad.getInt(7);
				double mathCredits = pathToGrad.getDouble(6);
				double resCredits = pathToGrad.getDouble(4);
				double totCredits = pathToGrad.getDouble(2);
				String canGrad = pathToGrad.getString(8);
				
				System.out.println("\n" + "Seminar courses taken: " + seminarCourse);
				System.out.println("Math credits taken: " + mathCredits);
				System.out.println("Research credits taken: " + resCredits);
				System.out.println("Total credits taken: " + totCredits);
				System.out.println("Fulfills the requirement for graduation: " + canGrad);
				System.out.println("------------------------------------");
			}
			

		} catch (SQLException e) {
			System.out.println("Cannot retrieve information for this student");
		}
		
	}


	static void registerStudent(Connection conn, String student, String course)
	{
		String getReg = ("SELECT * FROM Registrations WHERE student = " + "'" + student + "'" + " AND course = " +
				"'" + course + "'");
		String courseQueue = ("SELECT * FROM CourseQueuePositions WHERE student = " + "'" + student + "'" + " AND course = " +
				"'" + course + "'");
		
		
		try {
				
			String insertReg = ("INSERT INTO Registrations(student, course) VALUES (" + "'" + student + "', " + "'" + course + "'" + ")");
			
			Statement regStatement = conn.createStatement();
			ResultSet lol = regStatement.executeQuery(insertReg);
			
			Statement queueStmt = conn.createStatement();
			ResultSet courseQueueing = queueStmt.executeQuery(courseQueue);
			
			Statement getRegStmt = conn.createStatement();
			ResultSet getRegistration = getRegStmt.executeQuery(getReg);
			
			
			if(courseQueueing.next()) {
				if(student.equals(courseQueueing.getString(1)) && course.equals(courseQueueing.getString(4))) {
					System.out.println("Course " + course + " is full, you are put in the waiting list as number " + courseQueueing.getInt(5));
				}
			}
			else if(getRegistration.next()) {
				if(student.equals(getRegistration.getString(1)) && course.equals(getRegistration.getString(5) ) && getRegistration.getString(6).equals("Registered")) {
					System.out.println("You are now successfully registered to course " + course + " " + getRegistration.getString(3) + "!");
				}
			}			
			
			
		} catch (SQLException e) {
			System.out.println("Cannot register to the course");
		}
	}

	static void unregisterStudent(Connection conn, String student, String course)
	{
		String delReg = ("DELETE FROM Registrations WHERE student = " + "'" +student + "'" + " AND course = " + "'" + course + "'");

			try {
				Statement delStmt = conn.createStatement();
				int res = delStmt.executeUpdate(delReg);
				
				if (res > 0) {
					System.out.println("You have been unregistered from course " + course );
				}
				else {
					System.out.println("Cannot unregister from course " + course);
				}
			} catch (SQLException e) {
				System.out.println("Error: cannot perform this action");
			}

	}
}